package com.globo.opensocial;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import com.yahoo.platform.yui.compressor.CssCompressor;

/**
 * This file contains a css file
 * 
 * @author Jorge Falcao
 * 
 */
public class Css extends Content {

	/**
	 * Load a css file.
	 * 
	 * @param app
	 * @param file
	 */
	Css(Application app, File file) {
		super(app, file);
	}

	/**
	 * Write CSS Code on OutputStream TODO: Optimize the Css code.
	 * 
	 * @param os
	 * @throws IOException
	 */
	public void writeCode(Writer out) throws IOException {

		if (this.file == null) {
			System.err.println("[ERRO] Oppss...css file NULL!");
			return;
		}

		System.out.println("[INFO] Reading CSS " + file.getName());

		if (!file.isFile()) {
			System.err.println("[ERRO] File Don't exists :( " + file.getName());
			return;
		}

		if (Application.getInstance().isDebug()) {
			out.append(getContent());
		} else {
			Reader in = new StringReader(getContent());

			try {

				CssCompressor compressor = new CssCompressor(in);

				// Close the input stream first, and then open the output
				// stream,
				// in case the output file should override the input file.
				in.close();
				in = null;

				compressor.compress(out, -1);

			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.err.println("[INFO] Finished");

	}

	/**
	 * Write the <style> tag.
	 * 
	 * @param os
	 * @throws IOException
	 */
	static public void writeOpenTag(Writer os) throws IOException {
		os.append("<style>");
	}

	/**
	 * Write the </style> tag.
	 * 
	 * @param os
	 * @throws IOException
	 */
	static public void writeCloseTag(Writer os) throws IOException {
		os.append("</style>\n");
	}

}
